/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.workflow.service.usertask.impl;

import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.TreeUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.model.dd.DicInfoVo;
import com.je.workflow.service.usertask.WfProcessManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 流程待办首页加载分类树
 */
@Component(value = "wfProcessManager")
public class WfProcessManagerImpl implements WfProcessManager {

    @Autowired
    private MetaService metaService;
    @Autowired
    private MetaResourceService metaResourceService;
    @Autowired
    private CommonService commonService;

    public static final String ROOT_ID = "JDpyANm3A4aRwk0iAuL";

    public static final String DICTIONARY_ID = "gzRwXHFDlAziuwCs0G0";

    @Override
    public JSONTreeNode getProcessTree(DicInfoVo dicInfoVo) {
        Map<String, String> params = dicInfoVo.getParams();
        NativeQuery nativeQuery = NativeQuery.build();
        Boolean isNotFast = true;
        if (params != null) {
            String fast = params.get("fast");
            if (fast != null && fast.equals("1")) {
                nativeQuery.eq("SY_PARENT", ROOT_ID);
                isNotFast = false;
            }
        }
        nativeQuery.tableCode("JE_CORE_DICTIONARYITEM");
        nativeQuery.eq("DICTIONARYITEM_DICTIONARY_ID", DICTIONARY_ID);
        nativeQuery.eq("SY_FLAG", "1");
        nativeQuery.orderByAsc("SY_ORDERINDEX");
        if (isNotFast) {
            return getWorkFlowTypeChildrenTree(nativeQuery);
        } else {
            return getFastWorkFlowTypeChildrenTree(nativeQuery);
        }
    }

    private JSONTreeNode getWorkFlowTypeChildrenTree(NativeQuery nativeQuery) {
        List<Map<String, Object>> list = metaResourceService.selectMapByNativeQuery(nativeQuery);
        List<JSONTreeNode> jsonTreeNodeList = new ArrayList<>();
        jsonTreeNodeList.add(buildRootNode());
        for (Map<String, Object> child : list) {
            if (child.get("JE_CORE_DICTIONARYITEM_ID").equals(ROOT_ID)) {
                continue;
            }
            buildChild(child, jsonTreeNodeList);
        }
        return commonService.buildJSONNewTree(jsonTreeNodeList, ROOT_ID);
    }

    private JSONTreeNode buildRootNode() {
        JSONTreeNode root = TreeUtil.buildRootNode();
        root.setId(ROOT_ID);
        root.setExpandable(true);
        root.setExpanded(false);
        root.setLayer("0");
        root.setLeaf(false);
        return root;
    }

    private JSONTreeNode getFastWorkFlowTypeChildrenTree(NativeQuery nativeQuery) {
        List<Map<String, Object>> list = metaResourceService.selectMapByNativeQuery(nativeQuery);
        List<JSONTreeNode> jsonTreeNodeList = new ArrayList<>();
        jsonTreeNodeList.add(buildRootNode());
        for (Map<String, Object> child : list) {
            if (child.get("JE_CORE_DICTIONARYITEM_ID").equals(ROOT_ID)) {
                continue;
            }
            buildFastChild(child, jsonTreeNodeList);
        }
        return commonService.buildJSONNewTree(jsonTreeNodeList, ROOT_ID);
    }


    private void buildFastChild(Map<String, Object> child, List<JSONTreeNode> jsonTreeNodeList) {
        JSONTreeNode jsonTreeNode = new JSONTreeNode();
        jsonTreeNode.setCode((String) child.get("DICTIONARYITEM_ITEMCODE"));
        jsonTreeNode.setText((String) child.get("DICTIONARYITEM_ITEMNAME"));
        jsonTreeNode.setId((String) child.get("JE_CORE_DICTIONARYITEM_ID"));
        jsonTreeNode.setNodeType("LEAF");
        jsonTreeNode.setParent((String) child.get("SY_PARENT"));
        if (child.get("DICTIONARYITEM_ICON") == null) {
            jsonTreeNode.setIcon("");
        } else {
            jsonTreeNode.setIcon((String) child.get("DICTIONARYITEM_ICON"));
        }
        if (child.get("DICTIONARYITEM_ICONCOLOR") == null) {
            jsonTreeNode.setIconColor("");
        } else {
            jsonTreeNode.setIconColor((String) child.get("DICTIONARYITEM_ICONCOLOR"));
        }
        jsonTreeNodeList.add(jsonTreeNode);
    }

    private void buildChild(Map<String, Object> child, List<JSONTreeNode> jsonTreeNodeList) {
        JSONTreeNode jsonTreeNode = new JSONTreeNode();
        jsonTreeNode.setCode((String) child.get("DICTIONARYITEM_ITEMCODE"));
        jsonTreeNode.setText((String) child.get("DICTIONARYITEM_ITEMNAME"));
        jsonTreeNode.setId((String) child.get("JE_CORE_DICTIONARYITEM_ID"));
        jsonTreeNode.setNodeType("LEAF");
        if (child.get("DICTIONARYITEM_ICON") == null) {
            jsonTreeNode.setIcon("");
        } else {
            jsonTreeNode.setIcon((String) child.get("DICTIONARYITEM_ICON"));
        }

        if (child.get("DICTIONARYITEM_ICONCOLOR") == null) {
            jsonTreeNode.setIconColor("");
        } else {
            jsonTreeNode.setIconColor((String) child.get("DICTIONARYITEM_ICONCOLOR"));
        }

        jsonTreeNode.setParent((String) child.get("SY_PARENT"));
        List<DynaBean> dynaBeans = metaService.select("JE_WORKFLOW_PROCESSINFO",
                ConditionsWrapper.builder().eq("PROCESSINFO_TYPE_CODE", child.get("DICTIONARYITEM_ITEMCODE"))
        .eq("SY_STATUS","1"));
        for (DynaBean dynaBean : dynaBeans) {
            jsonTreeNode.getChildren().add(buildChildTree(dynaBean, jsonTreeNode));
        }
        jsonTreeNodeList.add(jsonTreeNode);
    }

    public JSONTreeNode buildChildTree(DynaBean dynaBean, JSONTreeNode jsonTreeNode) {
        JSONTreeNode node = new JSONTreeNode();
        node.setId(dynaBean.getStr("PROCESSINFO_KEY"));
        node.setCode(dynaBean.getStr("PROCESSINFO_FUNC_CODE"));
        node.setText(dynaBean.getStr("PROCESSINFO_NAME"));
        node.setNodeType("WF");
        node.setNodeInfoType("");
        node.setIcon("");
        node.setParent(jsonTreeNode.getId());
        node.setChecked(false);
        node.setLayer(jsonTreeNode.getLayer() + 1);
        return node;
    }

}
